package com.example.jpa.demo_jpa.controller;


import com.example.jpa.demo_jpa.dao.PhoneTypeDao;
import com.example.jpa.demo_jpa.model.PhoneType;
import com.example.jpa.demo_jpa.service.PhoneTypeService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class PhoneTypeController {
    @Autowired
    PhoneTypeService phoneTypeService;
    @Autowired
    PhoneTypeDao phoneTypeDao;

    //查看所有
    @RequestMapping("/")
    public String phone_type1(Model model){
        List<PhoneType> phoneTypes = phoneTypeService.findAll();
        model.addAttribute("phones",phoneTypes);
        return "phone_type.html";
    }

    //查看所有
    @RequestMapping("/phone")
    public String phone_type(Model model){
        List<PhoneType> phoneTypes = phoneTypeService.findAll();
        model.addAttribute("phones",phoneTypes);
        return "phone_type.html";
    }

    //跳转去添加页面
    @GetMapping("/add")
    public String toAdd(Model model){
        return "phoneType/add.html";
    }

    //添加操作
    @PostMapping("/add")
    public String addPT(PhoneType phoneType){
       //保存信息
        phoneTypeService.save(phoneType);
        //重定向到列表页面
        return "redirect:/phone";
    }

    //跳转到更新页面
    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable("id") String id,  Model model){
        //根据id查出来的信息
        PhoneType phoneType =  phoneTypeService.findById(id);
        //将信息返回给页面
        model.addAttribute("phones",phoneType);
        return "phoneType/update.html";
    }

    //更新操作
    @PostMapping("/update")
    public String updatePT(PhoneType phoneType){
        phoneTypeService.save(phoneType);
        return "redirect:/phone";
    }

    //通过号码查询
   @RequestMapping("/searchByNumber")
    public String findByNumber(HttpServletRequest request, Model model){
        //获取搜索框的值
        String search_input = request.getParameter("search_number");
        //根据号码查询的信息
       PhoneType phones2 = phoneTypeDao.findByNumber(search_input);
       System.out.println(phones2);
        //将信息返回给页面
        model.addAttribute("phones",phones2);
        return "phone_type.html";
    }


    //删除操作
    @GetMapping("/delPhone/{id}")
    public String delPhone(@PathVariable("id") String id){
        phoneTypeService.delete(id);
        return "redirect:/phone";
    }
}
